package com.glodon.paas.framework.registry.server.health;

import com.glodon.paas.framework.registry.server.ServerManager;
import com.glodon.paas.framework.registry.server.exception.RegistryServerRuntimeException;
import com.glodon.paas.framework.registry.server.zk.watcher.ServiceRootWatcher;
import com.glodon.paas.framework.registry.server.zk.watcher.ServiceWatcher;
import org.apache.zookeeper.ZooKeeper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * A spring bean which do health checking for SRDS
 *
 * @author Don Li
 */
public class HealthChecker {
    private final Logger LOGGER = LoggerFactory.getLogger(HealthChecker.class);

    @Autowired
    private ServerManager manager;

    private final String servicesPath;

    public HealthChecker(String servicesPath) {
        this.servicesPath = servicesPath;
    }

    public void init() {
//        registerWatchers();
//        LOGGER.info("HealthChecker has been initialized");
    }

    private void registerWatchers() {
        ZooKeeper zk = manager.getZk();
        try {
            // set watcher for services
            List<String> services = zk.getChildren(servicesPath, new ServiceRootWatcher(zk));
            // set watcher for each service
            for (String service : services) {
                String path = servicesPath + "/" + service;
                zk.getChildren(path, new ServiceWatcher(zk));
            }
        } catch (Exception e) {
            LOGGER.error("Error setting watchers for services");
            throw new RegistryServerRuntimeException(e);
        }
    }
}
